<script lang="ts" setup>
import { computed, ref } from 'vue'
import { NButton, NInput, NPopconfirm, NSelect,NModal,NCard, useMessage } from 'naive-ui'
import type { Language, Theme } from '@/store/modules/app/helper'
import { SvgIcon } from '@/components/common'
import {useAppStore, useUserStore, useAuthStore, usePromptStore} from '@/store'
import type { UserInfo } from '@/store/modules/user/helper'
import { getCurrentDate } from '@/utils/functions'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { t } from '@/locales'
import {checkQr, getQrcode,saveUserinfo,wxloginforCode} from "@/api";
import { onMounted, onDeactivated,onBeforeMount,onUnmounted } from 'vue'
import { getLocalState,setLocalState } from '@/store/modules/user/helper'
import { getLocalState as chatLocalState ,setLocalState as  chatSetLocalState} from '@/store/modules/chat/helper'
import {useRouter} from "vue-router";

const appStore = useAppStore()
const userStore = useUserStore()
const auth = useAuthStore()
const promptStore = usePromptStore()
const { currentRoute } = useRouter();
const route = currentRoute.value;
const router = useRouter()

const { isMobile } = useBasicLayout()

const ms = useMessage()

const theme = computed(() => appStore.theme)

const userInfo = computed(() => userStore.userInfo)

const token = ref(auth.token ?? '')

const avatar = ref(userInfo.value.avatar ?? '')

const name = ref(userInfo.value.name ?? '')
const apiKey = ref(userInfo.value.apiKey ?? '')

const description = ref(userInfo.value.description ?? '')

const promptList = ref<any>(promptStore.promptList)

const language = computed({
  get() {
    return appStore.language
  },
  set(value: Language) {
    appStore.setLanguage(value)
  },
})

const themeOptions: { label: string; key: Theme; icon: string }[] = [
  {
    label: 'Auto',
    key: 'auto',
    icon: 'ri:contrast-line',
  },
  {
    label: 'Light',
    key: 'light',
    icon: 'ri:sun-foggy-line',
  },
  {
    label: 'Dark',
    key: 'dark',
    icon: 'ri:moon-foggy-line',
  },
]



const languageOptions: { label: string; key: Language; value: Language }[] = [
  { label: '简体中文', key: 'zh-CN', value: 'zh-CN' },
  { label: '繁體中文', key: 'zh-TW', value: 'zh-TW' },
  { label: 'English', key: 'en-US', value: 'en-US' },
]
const showQrcode = ref(false);
const Qrcode = ref('https://chatp.zzhomee.cn/touxiang.jpg');
const ticket = ref(null);
const timer = ref(null);

function updateUserInfo(options: Partial<UserInfo>) {
	console.log(token.value)

  userStore.updateUserInfo(options)

  ms.success(t('common.success'))
}

function wxlogin(){
	showQrcode.value = true
	console.log(showQrcode)
	getQrcode().then((res) => {
		console.log(res)

		if (res.code != 0){
			ms.error(res.msg)
			return
		}

		Qrcode.value = res.data.url
		ticket.value = res.data.ticket

		timer.value = window.setInterval(() => {
			setTimeout(() => {
				bindUser()
			},0)
		},3000)
	})
}

function bindUser(){
	checkQr(ticket.value).then((res) => {
		console.log(res)


		if (res.code != 0){
			ms.error(res.msg)
			return
		}

		if (res.data.isScene){
			cleartime()
			auth.setToken(res.data.openid)
			token.value = res.data.openid

			showQrcode.value = false
			if (res.data.userStorage){
				setLocalState({
					userInfo:{
						...res.data.userStorage
					}
				})
			}

			if (res.data.chatStorage){
				chatSetLocalState(res.data.chatStorage)
			}
			window.location.reload()

		}

	})

}

function handleReset() {
  userStore.resetUserInfo()
  ms.success(t('common.success'))
  window.location.reload()
}

function handleLogOut() {
	auth.removeToken()
	ms.success(t('common.success'))
	// router.push('/')
	window.location.href = '/';
}

function handleSave(){
	/*if (apiKey.value === '' || !apiKey.value) {
		ms.error('请先设置use key~')
		return
	}*/

	let ua = navigator.userAgent.toLowerCase();
	let isWeixin = ua.indexOf('micromessenger') != -1;
	let url = window.location.href
	//http://chat.renren.club/?code=031Ca20w3gHqC03ttb1w34g6FC0Ca20C#/chat/1002




	if (token.value === '' || !token.value) {
		//开始登陆
		if (isWeixin && url.indexOf('code') <=0){
			getWxCode()
		}else{
			wxlogin()
		}
		return
	}

	let data = {
		chatStorage:chatLocalState(),
		userStorage:getLocalState().userInfo
	}
	saveUserinfo(data).then((res) => {
		console.log(res)

		if (res.code != 0){
			ms.error(res.msg)
			return
		}

		ms.success(t('common.success'))
		// window.location.reload()
	})
}

function exportData(): void {
  const date = getCurrentDate()
  const data: string = localStorage.getItem('chatStorage') || '{}'
  const jsonString: string = JSON.stringify(JSON.parse(data), null, 2)
  const blob: Blob = new Blob([jsonString], { type: 'application/json' })
  const url: string = URL.createObjectURL(blob)
  const link: HTMLAnchorElement = document.createElement('a')
  link.href = url
  link.download = `chat-store_${date}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

function importData(event: Event): void {
  const target = event.target as HTMLInputElement
  if (!target || !target.files)
    return

  const file: File = target.files[0]
  if (!file)
    return

  const reader: FileReader = new FileReader()
  reader.onload = () => {
    try {
      const data = JSON.parse(reader.result as string)
      localStorage.setItem('chatStorage', JSON.stringify(data))
      ms.success(t('common.success'))
      location.reload()
    }
    catch (error) {
      ms.error(t('common.invalidFileFormat'))
    }
  }
  reader.readAsText(file)
}

function clearData(): void {
  localStorage.removeItem('chatStorage')
  location.reload()
}

function handleImportButtonClick(): void {
  const fileInput = document.getElementById('fileInput') as HTMLElement
  if (fileInput)
    fileInput.click()
}

function cleartime(){
	window.clearInterval(timer.value)
}

function getWxCode() {
	const AppId = 'wx8b3a080783d3a8d0';
	let state = encodeURIComponent("http://chat.renren.club");
	let redirectURL = encodeURIComponent('http://mp.klgeek.com/wx/wxAuth/redirectURL');
	let base = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=`;
	window.location.href = base + AppId +
		`&redirect_uri=` + redirectURL +
		`&response_type=code&scope=snsapi_base&state=`+state+`&connect_redirect=1#wechat_redirect`;
}

function init(){

}



// onMounted(() => init())
onBeforeMount(() => cleartime())
onDeactivated(() => cleartime())
onUnmounted(() => cleartime())

</script>

<template>
  <div class="p-4 space-y-5 min-h-[200px]">
    <div class="space-y-6">
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">{{ $t('setting.avatarLink') }}</span>
        <div class="flex-1">
          <NInput v-model:value="avatar" placeholder="输入链接，可以个性化头像" />
        </div>
        <NButton size="tiny" text type="primary" @click="updateUserInfo({ avatar })">
          {{ $t('common.save') }}
        </NButton>
      </div>

      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]" >{{ $t('setting.apiKey') }}</span>
        <div class="w-[200px]">
          <NInput v-model:value="apiKey" placeholder="请输入user key" />
        </div>
        <NButton size="tiny" text type="primary" @click="updateUserInfo({ apiKey })">
          {{ $t('common.save') }}
        </NButton>
      </div>
      <div
        class="flex items-center space-x-4"
        :class="isMobile && 'items-start'"
      >
        <span class="flex-shrink-0 w-[100px]">{{ $t('setting.chatHistory') }}</span>

        <div class="flex flex-wrap items-center gap-4">
          <NButton size="small" @click="exportData">
            <template #icon>
              <SvgIcon icon="ri:download-2-fill" />
            </template>
            {{ $t('common.export') }}
          </NButton>

          <input id="fileInput" type="file" style="display:none" @change="importData">
          <NButton size="small" @click="handleImportButtonClick">
            <template #icon>
              <SvgIcon icon="ri:upload-2-fill" />
            </template>
            {{ $t('common.import') }}
          </NButton>

          <NPopconfirm placement="bottom" @positive-click="clearData">
            <template #trigger>
              <NButton size="small">
                <template #icon>
                  <SvgIcon icon="ri:close-circle-line" />
                </template>
                {{ $t('common.clear') }}
              </NButton>
            </template>
            {{ $t('chat.clearHistoryConfirm') }}
          </NPopconfirm>
        </div>
      </div>
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">{{ $t('setting.theme') }}</span>
        <div class="flex flex-wrap items-center gap-4">
          <template v-for="item of themeOptions" :key="item.key">
            <NButton
              size="small"
              :type="item.key === theme ? 'primary' : undefined"
              @click="appStore.setTheme(item.key)"
            >
              <template #icon>
                <SvgIcon :icon="item.icon" />
              </template>
            </NButton>
          </template>
        </div>
      </div>
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">{{ $t('setting.language') }}</span>
        <div class="flex flex-wrap items-center gap-4">
          <NSelect
            style="width: 140px"
            :value="language"
            :options="languageOptions"
            @update-value="value => appStore.setLanguage(value)"
          />
        </div>
      </div>
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">{{ $t('setting.resetUserInfo') }}</span>
        <NButton size="small" @click="handleReset">
          {{ $t('common.reset') }}
        </NButton>

				<template v-if="token">
					<NButton  size="small" @click="handleLogOut">
						退出登录
					</NButton>
				</template>

      </div>
			<div class="flex items-center space-x-4">
				<span class="flex-shrink-0 w-[100px]">{{ $t('setting.saveUserInfo') }}</span>
				<NButton size="small" @click="handleSave">
					保存/获取
				</NButton>
			</div>
    </div>
  </div>

	<NModal v-model:show="showQrcode">
		<NCard
			style="width: 410px"
			title="微信扫码登录"
			:bordered="false"
			size="huge"
			role="dialog"
			aria-modal="true"
		>
			<template #header-extra></template>
			<img :src="Qrcode" style="width: 400px"/>
			<template #footer></template>
		</NCard>
	</NModal>
</template>
